using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WinSSHMenu
{
    /// <summary>
    /// This class implements some simple helper routines
    /// </summary>
    class FileUtil
    {
        String appPath = null;
        string puttyExe = null;
        String appDir = null;

        public FileUtil()
        {
            appDir =
                Path.GetFullPath(Path.Combine(Environment.GetFolderPath(
                    Environment.SpecialFolder.ApplicationData), ".."));

            appPath = appDir + "\\" + Properties.Settings.Default.AppDir;
            if (!Directory.Exists(appPath))
            {
                Directory.CreateDirectory(appPath);
            }
            appPath += "\\" + Properties.Settings.Default.MenuFile;

            puttyExe = Properties.Settings.Default.PuttyPath;

        }

        /// <summary>
        /// This method reads the server list from the xml file on disk and
        /// loads it into the specified tree view control
        /// </summary>
        /// <param name="HostList">The treeview control into which
        /// to load the server list</param>
        public void LoadServerList(TreeView HostList)
        {

            // Load the existing tree from disk (if it exists)
            if (File.Exists(appPath))
            {
                TreeViewSerializer serializer = new TreeViewSerializer();
                serializer.DeserializeTreeView(HostList, appPath);
            }
        }

        /// <summary>
        /// This method will serialize the server list contained in the 
        /// specified treeview control and write it to disk as an xml file
        /// </summary>
        /// <param name="HostList"></param>
        public void SaveServerList(TreeView HostList)
        {
            // Load the existing tree from disk
            TreeViewSerializer serializer = new
                TreeViewSerializer();
            serializer.SerializeTreeView(HostList, appPath);
        }


        /// <summary>
        /// This method takes care of launching a putty process for the 
        /// specified host name.
        /// </summary>
        /// <param name="hostName">The host name to connect to.</param>
        /// <param name="windowTitle">The window title for the 
        /// connection</param>
        public void LaunchSSHProcess(String hostName, String windowTitle)
        {
            // Make sure if have the putty exe first.  If not ask the user
            // if they want to find it. 
            if (!File.Exists(puttyExe))
            {
                DialogResult result = 
                    MessageBox.Show("Did not find PuTTY exe at " + 
                                    puttyExe + " would you like to locate " +
                                    "PuTTY now?",
                                    "Caption", MessageBoxButtons.YesNo, 
                                    MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    WinSSHMenuPreferences pref = new WinSSHMenuPreferences();
                    pref.prefTabs.SelectedTab = pref.prefTabs.TabPages[2];
                    pref.ShowDialog();
                    puttyExe = Properties.Settings.Default.PuttyPath;
                }
                else
                {
                    return;
                }
            }

            System.Diagnostics.ProcessStartInfo psi =
                new System.Diagnostics.ProcessStartInfo(puttyExe);
            psi.RedirectStandardOutput = true;
            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.Arguments = hostName;
            System.Diagnostics.Process testProcess;
            testProcess = System.Diagnostics.Process.Start(psi);
            System.IO.StreamReader myOutput = testProcess.StandardOutput;
        }

        public void LaunchSSHProcess(ToolStripItemCollection items)
        {
            for (int i = 0; i < items.Count; i++)
            {
                if (items[i].Text.Equals("Open All Windows") ||
                    items[i].Text.Equals(""))
                {
                    continue;
                }
                ToolStripMenuItem ThisItem =
                    (ToolStripMenuItem)items[i];
                String arg = ThisItem.Tag.ToString();
                FileUtil util = new FileUtil();
                util.LaunchSSHProcess(arg, ThisItem.Text);
            }
        }

        /// <summary>
        /// The application path (in the user's home directory) usually 
        /// [home_dir]/.WinSSHMenu
        /// </summary>
        public string AppPath
        {
            get { return this.appPath; }
            set { this.appPath = value; }
        }

        /// <summary>
        /// Path to putty exe.
        /// </summary>
        public string PuttyExe
        {
            get { return this.puttyExe; }
            set { this.puttyExe = value; }
        }
        
        public string AppDir
        {
            get { return this.appDir; }
            set { this.appDir = value; }
        }

        /// <summary>
        /// This method will create a copy of the server list in the default
        /// app directory with a .bak extension.  
        /// </summary>
        public void ReplaceServerList(String newFileName)
        {
            DateTime dt = DateTime.Now;
            String str = "_" + dt.ToString("yyyy-MM-dd-HH-mm") + ".bak";
            String backupFileName = appPath + str;
            
            // First back up our original
            File.Copy(appPath, appPath + str);

            // Now copy our new one onto our existing one
            File.Copy(newFileName, appPath, true);
        }

    }
}
